package com.example.good.controller;

import com.example.good.entity.User;
import com.example.good.service.IUserService;
import com.example.good.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("user")
//42267
@CrossOrigin(value = "http://localhost:8086")
//@CrossOrigin(value = "http://192.168.11.134:8086")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("register")
    public JsonResult<Void> register(User user) {
        userService.register(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(
            String username,
            String password,
            HttpSession session) {
        System.out.println(username+"&&&&&"+password);
        User user = userService.login(username, password);
        session.setAttribute("good_uid", user.getUid());
        session.setAttribute("good_usn", user.getUsername());
        return new JsonResult<>(OK, user);
    }
    @RequestMapping("forget_psw")
    public JsonResult<Void> forgetPsw(
            String username,
            String phone){
        userService.forgetPsw(username,phone);
        return new JsonResult<>(OK);
    }
    @RequestMapping("check_psw")
    public JsonResult<Void> checkPsw(
            String oldPassword,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.checkPassword(uid,username,oldPassword);
        return new JsonResult<>(OK);
    }
    @RequestMapping("change_psw")
    public JsonResult<Void> changePsw(
            String newPassword,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,newPassword);
        session.setAttribute("good_uid","");
        session.setAttribute("good_usn","");
        return new JsonResult<>(OK);
    }
    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(
            HttpSession session){
        Integer uid = getUidFromSession(session);
        User user = userService.getByUid(uid);
        return new JsonResult<>(OK,user);
    }
    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(
            User user,
            HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }
}
